package com.hjm.project.bankExpenditure.bankExpenditure.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.hjm.common.utils.*;
import com.hjm.common.utils.fastdfs.FastDFSClient;
import com.hjm.common.utils.request.AutoLoadData;
import com.hjm.common.utils.security.ShiroUtils;
import com.hjm.framework.config.BlueConfig;
import com.hjm.framework.config.CustomConfig;
import com.hjm.project.bankExpenditure.bankExpenditure.domain.PosOrder;
import com.hjm.project.terminal.manufacturer.service.IManufacturerService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import com.hjm.framework.aspectj.lang.annotation.Log;
import com.hjm.framework.aspectj.lang.enums.BusinessType;
import com.hjm.project.bankExpenditure.bankExpenditure.domain.BankExpenditure;
import com.hjm.project.bankExpenditure.bankExpenditure.service.IBankExpenditureService;
import com.hjm.framework.web.controller.BaseController;
import com.hjm.framework.web.domain.AjaxResult;
import com.hjm.framework.web.page.TableDataInfo;
import uk.ac.cam.cl.mgk25.jbigkit.JBIG;

import javax.annotation.Resource;

/**
 * 消费Controller
 * 
 * @author LOVE
 * @date 2020-11-27
 */
@Controller
@RequestMapping("/bankExpenditure/bankExpenditure")
public class BankExpenditureController extends BaseController
{
    private String prefix = "bankExpenditure/bankExpenditure";

    @Autowired
    private IBankExpenditureService bankExpenditureService;
    @Resource
    private IManufacturerService manufacturerService;

    @RequiresPermissions("bankExpenditure:bankExpenditure:view")
    @GetMapping()
    public String bankExpenditure(ModelMap mmap) throws Exception {
        List<Map> manufacturer = manufacturerService.getManufacturer(ShiroUtils.isAgent() ? ShiroUtils.getLoginAgentNum() : null);
        mmap.put("manufacturer",manufacturer);
        return prefix + "/bankExpenditure";
    }

    /**
     * 查询消费列表
     */
    @RequiresPermissions("bankExpenditure:bankExpenditure:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(BankExpenditure bankExpenditure)
    {
        startPage();
        Map data = new HashMap();
        data = bankExpenditureService.selectBankExpenditureCount(bankExpenditure);
        List<BankExpenditure> list = bankExpenditureService.selectBankExpenditureList(bankExpenditure);
        if (CollectionUtils.isNotEmpty(list)) {
            for (BankExpenditure expenditure : list) {
                expenditure.setPan(Utils.dealCard(expenditure.getPan()));
                expenditure.setRc(CodeFormat.code.get(expenditure.getRc()) == null?expenditure.getRc():expenditure.getRc() + "-" + CodeFormat.code.get(expenditure.getRc()));
            }
        }
        return getDataTable(list,data);
    }

    /**
     * 导出消费列表
     */
    @RequiresPermissions("bankExpenditure:bankExpenditure:export")
    @Log(title = "消费", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(BankExpenditure bankExpenditure) throws Exception {
        return bankExpenditureService.exportDetailExcel(bankExpenditure);
    }

    /**
     * 新增消费
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存消费
     */
    @RequiresPermissions("bankExpenditure:bankExpenditure:add")
    @Log(title = "消费", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(BankExpenditure bankExpenditure)
    {
        return toAjax(bankExpenditureService.insertBankExpenditure(bankExpenditure));
    }

    /**
     * 修改消费
     */
    @GetMapping("/edit/{serial}")
    public String edit(@PathVariable("serial") Long serial, ModelMap mmap)
    {
        BankExpenditure bankExpenditure = bankExpenditureService.selectBankExpenditureById(serial);
        mmap.put("bankExpenditure", bankExpenditure);
        return prefix + "/edit";
    }

    /**
     * 修改保存消费
     */
    @RequiresPermissions("bankExpenditure:bankExpenditure:edit")
    @Log(title = "消费", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(BankExpenditure bankExpenditure)
    {
        return toAjax(bankExpenditureService.updateBankExpenditure(bankExpenditure));
    }

    /**
     * 删除消费
     */
    @RequiresPermissions("bankExpenditure:bankExpenditure:remove")
    @Log(title = "消费", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(bankExpenditureService.deleteBankExpenditureByIds(ids));
    }


    /**
     * 获取签购单
     */
    @RequiresPermissions("bankExpenditure:bankExpenditure:getQianGouDan")
    @GetMapping("/getQianGouDan")
    public String getQianGouDan(BankExpenditure bankExpenditure , ModelMap mmap)
    {
        String serial=bankExpenditure.getSerial().toString();
        String status=bankExpenditure.getStatus();
        String postype="dqian";
        if (!"0".equals(status)) {
            mmap.put("error", "请选择交易成功数据");
            return prefix +"/outQianGouDan";
        }
        //根据流水号查看签购单
        FileOutputStream fis = null;
        String signPath = "";
        String filepath = "";
        //获取请求路径
        String ip = CustomConfig.getImgUrl();
        //读取内网ip
        String neiIP = AutoLoadData.picrequestneiwangip + "/";
        try {
            Map dataMap = bankExpenditureService.selectSign(serial);
            Object ss = dataMap.get("SIGNATURE");
            PosOrder order = getPosorder(dataMap);
            //根据流水号查询小票是否存在
            Map map = bankExpenditureService.selectSignEx(serial);
            //存在小票  直接用
            if (map != null) {
                String sign_pic_path = (String) map.get("SIGN_PIC_PATH");

                mmap.put("signPath", ip + sign_pic_path);
            } else {
                //需要签名
                if (ss != null) {
                    //将ss转换为签名图片
                    filepath = BlueConfig.getProfile() + "/";
                    filepath = filepath + "qianzi" + System.currentTimeMillis();
                    File file = new File(filepath + ".jbig");
                    fis = new FileOutputStream(file);
                    fis.write(Utils.hexStringToBytes(ss.toString()));
                    fis.flush();
                    //将jbig转换成bmp
                    JBIG.jbg2bmp(filepath + ".jbig", filepath + ".bmp");
                    File filebmp = new File(filepath + ".bmp");
                    Map<String, String> metaList = new HashMap<String, String>();
                    metaList.put("fileName", filebmp.getName());
                    metaList.put("fileType", "qian");
                    //将签名文件上传 获取fid
                    String qianfid = FastDFSClient.uploadFile(filebmp, filebmp.getName(), metaList);
                    if ("-1".equals(qianfid)) {
                        mmap.put("error", "小票生成失败");
                        return prefix +"/outQianGouDan";
                    }

                    //获取背景图片
                    ClassPathResource resource = new ClassPathResource("static/img/bg.png");
                    signPath = BlueConfig.getProfile() + "/" + "sign_" + System.currentTimeMillis() + ".jpg";
                    //重绘图片
                    SignPicOrder.exportImg(order, resource.getInputStream(), filepath + ".bmp", true, signPath, true, postype);
                    File filetemp = new File(signPath);
                    metaList.put("fileName", filetemp.getName());
                    metaList.put("fileType", "signPic");
                    //上传签名小票
                    String signfid = FastDFSClient.uploadFile(filetemp, filetemp.getName(), metaList);
                    if ("-1".equals(signfid)) {
                        mmap.put("error", "小票生成失败");
                        return prefix +"/outQianGouDan";
                    }
                    Map<String, Object> data = new HashMap<>();
                    //添加数据
                    data.put("serial", serial);
                    data.put("qianm_pic_path", qianfid);
                    data.put("sign_pic_path", signfid);
                    data.put("resouce", 2);
                    //新增记录
                    bankExpenditureService.insertsignpic(data);

                    mmap.put("signPath", ip + signfid);
                } else {
                    //获取背景图片
                    ClassPathResource resource = new ClassPathResource("static/img/bg.png");
                    signPath = BlueConfig.getProfile() + "/" + "sign_" + System.currentTimeMillis() + ".jpg";
                    Map<String, String> metaList = new HashMap<String, String>();
                    //如果是mpos类型的话，查询小票
                    String mpossigpic = "";
                    if ("mpos".equals(postype)) {
                        //查询Mpos小票信息
                        String fileid = bankExpenditureService.selectMposBySerial(serial);
                        if (fileid != null && !"".equals(fileid)) {
                            mpossigpic = neiIP + fileid;
                        } else {
                            postype = "mainqian";
                        }
                    } else {
                        mpossigpic = filepath + ".bmp";
                    }
                    //重绘图片
                    SignPicOrder.exportImg(order, resource.getInputStream(), mpossigpic, true, signPath, false, postype);
                    File filetemp = new File(signPath);
                    metaList.put("fileName", filetemp.getName());
                    metaList.put("fileType", "signPic");
                    //上传签名小票
                    String signfid = FastDFSClient.uploadFile(filetemp, filetemp.getName(), metaList);
                    if ("-1".equals(signfid)) {
                        mmap.put("error", "小票生成失败");
                        return prefix +"/outQianGouDan";
                    }
                    Map<String, Object> data = new HashMap<>();
                    //添加数据
                    data.put("serial", serial);
                    data.put("qianm_pic_path", "mianqian");
                    data.put("sign_pic_path", signfid);
                    data.put("resouce", 2);
                    //新增记录
                    bankExpenditureService.insertsignpic(data);

                    mmap.put("signPath", ip + signfid);
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                    //删除jbig
                    if (new File(filepath + ".jbig").exists()) {
                        new File(filepath + ".jbig").delete();
                    }
                    //删除bmp
                    if (new File(filepath + ".bmp").exists()) {
                        new File(filepath + ".bmp").delete();
                    }
                    //删除电子签名
                    if (new File(signPath).exists()) {
                        new File(signPath).delete();
                    }
                } catch (IOException e) {
                }
            }
        }
        return prefix + "/getQianGouDan";
    }

    public PosOrder getPosorder(Map dataMap) {
        PosOrder order = new PosOrder();
        if (dataMap.get("INFO")!=null){
            String[] info=dataMap.get("INFO").toString().split(",");
            //商户名称
            order.setMerchantName(info[1]== null ? "" : info[1] + "");
            //商户编号
            order.setMerchantNo(info[0] == null ? "" : info[0] + "");
        }else {
            //商户名称
            order.setMerchantName("");
            //商户编号
            order.setMerchantNo("");
        }
        //卡类型
        order.setCardtype(dataMap.get("CARDTYPE") == null ? "" : dataMap.get("CARDTYPE") + "");
        //授权码
        order.setAir(dataMap.get("AIR") == null ? "" : dataMap.get("AIR") + "");
        //终端编号
        order.setBankpos(dataMap.get("CATI") == null ? "" : dataMap.get("CATI") + "");
        //内部参考号
        order.setTerno(dataMap.get("TERNO") == null ? "" : dataMap.get("TERNO") + "");
        //发卡行名称
        order.setBankname(dataMap.get("CARDNAME") == null ? "" : dataMap.get("CARDNAME") + "");
        //卡号
        order.setPan(dataMap.get("PAN") == null ? "" : dataMap.get("PAN") + "");
        //凭证号
        order.setStan(dataMap.get("STAN") == null ? "" : dataMap.get("STAN") + "");
        //参考号
        order.setRrno(dataMap.get("RRNO") == null ? "" : dataMap.get("RRNO") + "");
        //交易日期
        order.setRiqi(dataMap.get("LOCALDATE") + " " + dataMap.get("LOCALTIME"));
        //交易金额
        order.setAmount(dataMap.get("AMOUNT") == null ? "0.00" : dataMap.get("AMOUNT") + "");

        return order;
    }

    /**
     * 线上交易数据
     * @return
     */
    @RequiresPermissions("bankExpenditure:bankExpenditure:onLine")
    @GetMapping("/onLine")
    public String onLine()
    {
        return prefix + "/onLine";
    }

    /**
     * 查询线上交易数据列表
     */
    @RequiresPermissions("bankExpenditure:bankExpenditure:onLine")
    @PostMapping("/onLine")
    @ResponseBody
    public TableDataInfo onLine(@RequestParam Map<String, String> reqMap)
    {
        startPage();
        List<Map<String, String>> list = bankExpenditureService.selectOnLineList(reqMap);
        return getDataTable(list);
    }
}
